#include "printhandler.h"

PrintHandler::PrintHandler(QObject *parent) : QObject(parent)
{

}
void PrintHandler::setPage(QWebEnginePage *page){
    m_page=page;
}

void PrintHandler::print()
 {
    qDebug()<<"print";
     QPrinter printer(QPrinter::HighResolution);
     QPrintDialog dialog(&printer, m_page->view());
     if (dialog.exec() != QDialog::Accepted)
         return;
     printDocument(&printer);
 }
void PrintHandler::printDocument(QPrinter *printer)
 {
     QEventLoop loop;
     bool result;
     auto printPreview = [&](bool success) { result = success; loop.quit(); };
     m_page->print(printer, std::move(printPreview));
     loop.exec();
     if (!result) {
         QPainter painter;
         if (painter.begin(printer)) {
             QFont font = painter.font();
             font.setPixelSize(20);
             painter.setFont(font);
             painter.drawText(QPointF(10,25),
                              QStringLiteral("Could not generate print preview."));

             painter.end();
         }
     }
 }
void PrintHandler::printPreview()
{
    qDebug()<<"printPreview";
     if (!m_page)
         return;
     if (m_inPrintPreview)
         return;
     m_inPrintPreview = true;
     QPrinter printer;
     QPrintPreviewDialog preview(&printer, m_page->view());
     connect(&preview, &QPrintPreviewDialog::paintRequested,
             this, &PrintHandler::printDocument);
     preview.exec();
     m_inPrintPreview = false;
 }
